<template>
  <div class="wrap">
    <div class="header">
      <div class="left">
        <div class="search-item">
          <div style="display: inline-block; width: 300px;">
            <el-input
              size="small"
              style="width: 200px; margin-right: 10px; margin-bottom: 20px"
              v-model="queryParams.keyword"
              :placeholder="'搜索 希音店铺名或用户名'"
              @keyup.enter.native="changeOption(true)"
              clearable @clear="changeOption(false, 'clear')"
            ></el-input>
            <el-button size="small" type="primary" @click="changeOption(true)">{{ $t('common.search') }}</el-button>
          </div>
        </div>

        <div class="search-item my-date-picker">
          <el-date-picker v-model="queryDataDate" style="width: 200px;" type="date" placeholder="选择日期时间"></el-date-picker>
          <div style="display: inline-block; width: 48px; position: relative; left: -78px; color: red; font-size: 14px;">{{ weekendStr }}</div>
          <el-button style="position: relative; left: -38px;" size="small" :type="queryDataDate === date ? 'primary' : ''" @click="changeQueryDataDate(date)">今天</el-button>
          <el-button style="position: relative; left: -38px;" size="small" :type="queryDataDate === yesterday ? 'primary' : ''" @click="changeQueryDataDate(yesterday)">昨天</el-button>
          <!--<el-button size="small" :type="queryDataDate === saturday ? 'primary' : ''" @click="changeQueryDataDate(saturday)">星期六</el-button>-->
          <!--<el-button size="small" :type="queryDataDate === sunday ? 'primary' : ''" @click="changeQueryDataDate(sunday)">星期天</el-button>-->
        </div>
      </div>
      <div class="right">
        <div class="search-item">
          <el-button style="margin-bottom: 20px;" size="small" type="primary" @click="add()">添加图片</el-button>
        </div>
        <div class="search-item">
          <el-button size="small" :type="queryParams.isNotUploaded === 1 ? 'primary' : ''" @click="saveIsNotUploaded()">未上传图片店铺</el-button>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="page-wrap">
        <el-table
          v-loading="loading"
          :data="data"
          border
          v-tableHeight="{bottomOffset: 80}"
          height="100px"
          ref="tableData"
        >
          <el-table-column
            prop="accountName"
            :label="'希音店铺'"
            align="center"
            min-width="150"
          >
          </el-table-column>
          <el-table-column
            prop="userName"
            :label="'用户'"
            align="center"
            min-width="100"
          >
          </el-table-column>
          <el-table-column
            prop="imgNum"
            :label="'图片数量'"
            align="center"
            min-width="100"
          >
            <template slot-scope="{row}">
              <template v-if="row.imgNum > 0">
                {{ row.imgNum }}
              </template>
              <template v-else>
                <span style="cursor: pointer; color: #0099ff;" @click="save(row)">未上传</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="updateTime"
            :label="'最后一次编辑时间'"
            align="center"
            min-width="100"
          >
          </el-table-column>

          <el-table-column
            :label="$t('remittance.operate')"
            align="center"
            min-width="100"
          >
            <template slot-scope="{row}">
              <template v-if="row.imgNum > 0">
                <span style="cursor: pointer;" @click="save(row)">修改</span> |
                <span style="cursor: pointer;" @click="del(row)">删除</span>
              </template>
              <template v-else>
                <span style="cursor: pointer;" @click="save(row)">上传</span>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <span style="color: red; font-size: 14px;">所有的图片仅会保存60天时间，60天后对应图片与记录将被清除</span>
        <el-pagination
          @current-change="getData"
          :current-page.sync="queryParams.page"
          :page-size="queryParams.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100, 500, 1000]"
          @size-change="handleSizeChange"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      :title="'请选择需要上传图片的希音店铺'"
      :visible.sync="addInfoDialog"
      width="800px"
    >
      <div style="margin-top: -20px;" class="my-date-picker">图片日期：
        <el-date-picker v-model="addDataDate" type="date" placeholder="选择日期时间" style="margin-bottom: 10px;"></el-date-picker>
        <div>
          <el-input
            size="small"
            style="width: 200px; margin-bottom: 10px;"
            v-model="accountQueryParams.keyword"
            :placeholder="'搜索 希音店铺名或用户名'"
            @keyup.enter.native="accountChangeOption(true)"
            clearable @clear="accountChangeOption(false, 'clear')"
          ></el-input>
          <el-button size="small" type="primary" @click="accountChangeOption(true)" icon="el-icon-search"></el-button>
        </div>
      </div>
      <div style="margin-top: 20px;">
        <el-radio
          v-for="(item, index) in accountData"
          :key="index"
          v-model="addDataAccount"
          :label="item.id"
          style="width: 350px; margin-bottom: 20px;"
        >
          {{ item.nickName }}({{ item.userName }})
        </el-radio>
      </div>
      <el-pagination
        @current-change="getData"
        :current-page.sync="accountQueryParams.page"
        :page-size="accountQueryParams.pageSize"
        :total="accountTotal"
        layout="total, prev, pager, next, jumper"
      >
      </el-pagination>
      <div slot="footer">
        <el-button @click="addInfoDialog = false">取消</el-button>
        <el-button type="primary" @click="addControls" :loading="addInfoLoading" :disabled="addInfoDisable">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="'请选择上传图片的方式'"
      :visible.sync="saveInfoDialog"
      width="800px"
      :close-on-click-modal="false"
      :before-close="closeSaveInfoDialog"
    >
      <div style="margin-left: 40px; margin-top: -20px;">
        <span style="color: #0099ff; font-size: 16px;">
          {{ dataItem.accountName }} ({{ dataItem.userName }})
        </span>
      </div>

      <div style="margin-left: 40px; margin-top: 30px;">
        <div class="qrcode" style="display: inline-block;">
          <div id="pay-qrcode" ref="payQrcode"></div>
        </div>
        <div style="display: inline-block; margin-left: 30px; width: 260px; height: 150px; position: relative; top: -12px;">
          <b>手机拍照/图片上传</b>
          <br>
          <br>
          <span style="color: #7F7F7F; font-size: 13px;">请用手机扫描左侧二维码</span>
          <br>
          <br>
          <span style="color: #7F7F7F; font-size: 13px;">在打开的手机网页中，您可拍照或直接上传手机中的图片</span>
          <br>
          <br>
          <span style="color: red;">请根据平台的要求，上传相应的图片</span>
        </div>
      </div>

      <div style="margin-left: 30px; margin-top: -10px;">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess()"
          :before-upload="beforeAvatarUpload"
          :headers="uploadHeader"
          :disabled="uploadIng"
          :multiple="true"
          :concurrency="1"
          style="display: inline-block; margin-left: 20px; margin-right: 40px;"
        >
          <el-button type="primary" :loading="imgLoading" style="">
            本地上传（电脑）
          </el-button>

        </el-upload>
        <div style="display: inline-block;"><b>直接上传已保存在电脑中的图片</b></div>
      </div>

      <template v-if="imgArr.length > 0">
        <div style="margin-top: 30px; margin-left: 30px;">
          <div style="margin-left: 10px;">
            <span style="color: #0099ff; font-size: 16px;">
              已保存图片：
            </span>
          </div>
          <div v-for="(item, index) in imgArr" :key="index" style="margin-right: 10px; margin-left: 10px; display: inline-block; margin-top: 30px; margin-bottom: 30px;">
            <el-image
              class="zoomable-image"
              style="width: auto; height: 200px; vertical-align: top;"
              :src="item"
              :preview-src-list="imgArr"
            ></el-image>
            <span class="close-icon" @click="removeImage(index)">x</span>
          </div>
        </div>
      </template>

      <div slot="footer">
        <el-button type="primary" @click="closeSaveInfoDialog">完成</el-button>
        <!--<el-button type="primary" @click="saveControls" :loading="saveInfoLoading">保存</el-button>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSiAccountImageList,
  getSiAccountDataList,
  addSiAccountImageData,
  saveSiAccountImageData,
  delSiAccountImageData,
  getSiAccountImage,
} from "@/api/order";
import {deepCopy} from "@/utils";
import QRCode from "qrcodejs2";
import {getToken} from "@/utils/auth";
export default {
  name: "sheinImgList",
  computed:{
    addInfoDisable(){
      if (this.addDataAccount === '') {
        return true
      }
      if (this.addDataDate === null) {
        return true
      }
      return false
    },
  },
  data(){
    return {
      uploadIng: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/uploadSheinImage',
      uploadHeader: {
        Authorization: 'Bearer ' + getToken(),
      },

      // 图片材料列表
      queryParams:{
        page: 1,
        pageSize: 20,
        keyword: '',
        date: '',
        isNotUploaded: 0,
      },
      data: [],
      loading: false,
      total: 0,
      copyQueryParams:{},
      queryDataDate: '',
      date: '',
      yesterday: '',
      saturday: '',
      sunday: '',
      weekendStr: '',
      // 希音店铺列表
      accountQueryParams:{
        page: 1,
        pageSize: 20,
        keyword: '',
      },
      accountData: [],
      accountLoading: false,
      accountTotal:0,
      copyAccountQueryParams:{},

      // 添加弹窗
      addInfoDialog: false,
      addInfoLoading: false,
      addDataDate: '',
      addDataAccount: '',

      // 修改弹窗
      saveInfoDialog: false,
      saveInfoLoading: false,
      dataItem: {},
      imgArr: [],
      imgLoading: false,

      is_search: false,
      selectNum: 0,
    }
  },
  watch: {
    addDataDate(newDate) {
      // 当日期改变时触发
      if (newDate) {
        // 将字符串日期转换为日期对象
        const dateObj = new Date(newDate)
        // 将格式化后的日期值设置回 addDataDate 中
        this.addDataDate = this.formatDate(dateObj)
      }
    },
    queryDataDate(newDate) {
      // 当日期改变时触发
      if (newDate) {
        // 将字符串日期转换为日期对象
        const dateObj = new Date(newDate)

        // 如果是周六或周日，向后增加一天
        const dayOfWeek = dateObj.getDay()

        let dateStr = this.formatDate(dateObj)

        this.queryParams.date = dateStr

        this.weekendStr = ''

        if (dayOfWeek === 0) {
          this.weekendStr = '星期日'
        }

        if (dayOfWeek === 6) {
          this.weekendStr = '星期六'
        }

        this.queryDataDate = dateStr

        this.changeOption()
      } else {
        this.queryDataDate = ''
        this.queryParams.date = ''
        this.weekendStr = ''
        this.changeOption()
      }
    },
  },
  created() {
    this.copyQueryParams = deepCopy(this.queryParams)
    this.copyAccountQueryParams = deepCopy(this.accountQueryParams)
    this.getData()
    this.getAccountData()
  },
  updated () {
    this.$nextTick(() => {
      this.$refs['tableData'].doLayout();
    })
  },
  methods: {
    getData(){
      this.loading = true
      getSiAccountImageList(this.queryParams)
        .then(res=>{
          this.loading = false
          this.data = res.data
          this.total = res.info.total
          this.date = res.info.date
          this.yesterday = res.info.yesterday
          this.saturday = res.info.saturday
          this.sunday = res.info.sunday
          this.addDataDate = res.info.date
          if (this.selectNum <= 0) {
            this.changeQueryDataDate(this.date)
          }
          this.selectNum++
        })
    },
    getAccountData(){
      this.accountLoading = true
      getSiAccountDataList(this.accountQueryParams)
        .then(res=>{
          this.accountLoading = false
          this.accountData = res.data
          this.accountTotal = res.info.total
        })
    },
    add() {
      this.addInfoDialog = true
    },
    addControls() {
      this.addInfoLoading = true
      const postData = {
        accountId: this.addDataAccount,
        date: this.addDataDate,
      }
      addSiAccountImageData(postData)
        .then(res=>{
          if(res.error === 0){
            // 重置查询条件
            // this.queryParams = deepCopy(this.copyQueryParams)
            // this.accountQueryParams = deepCopy(this.copyAccountQueryParams)
            // this.queryDataDate = ''
            this.getData()
            this.getAccountData()
            this.addInfoLoading = false
            this.addInfoDialog = false
            this.save(res.info.dataInfo)
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    save(row) {
      this.dataItem = deepCopy(row)
      this.$nextTick(()=>{
        this.createQrCode()
      })
      this.getImgData()
      this.interval = setInterval(()=>{
        this.getImgData()
      },1500)
      this.saveInfoDialog = true
    },
    closeSaveInfoDialog() {
      this.dataItem = {}
      this.imgArr = []
      clearInterval(this.interval)
      this.getData()
      this.saveInfoDialog = false
    },
    removeImage(index) {
      this.$confirm('确定删除希音图片材料吗？', '删除图片', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: this.$t('remittance.confirm'),
        cancelButtonClass: this.$t('remittance.cancel'),
      })
        .then(res=>{
          const postData = {
            id: this.dataItem.id,
            imageUrl: this.imgArr[index],
            type: 'del',
          }
          this.imgArr.splice(index, 1);
          if (this.imgArr.length === 0) {
            this.imgArr = []
          }
          saveSiAccountImageData(postData)
            .then(res=>{
              if(res.error === 0){
                this.getImgData()
              } else {
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(res=>{

        });
    },
    saveControls() {

    },
    getImgData(){
      getSiAccountImage(this.dataItem.id)
        .then(res=>{
          if(res.error === 0){
            if (res.info.imageArr !== null) {
              this.imgArr = Object.values(res.info.imageArr)
            }
            this.imgLoading = false
          } else {
            this.$errorMessage(res.message)
          }
        })
    },
    del(row) {
      this.$confirm('确定删除该条希音图片材料记录吗？', '删除希音图片材料记录', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: this.$t('remittance.confirm'),
        cancelButtonClass: this.$t('remittance.cancel'),
      })
        .then(res=>{
          const postData = {
            id: row.id,
          }
          delSiAccountImageData(postData)
            .then(res=>{
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
              } else {
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(res=>{

        });
    },
    changeQueryDataDate(date) {
      this.queryDataDate = date
    },
    saveIsNotUploaded() {
      if (this.queryParams.isNotUploaded === 1) {
        this.queryParams.isNotUploaded = 0
      } else {
        this.queryParams.isNotUploaded = 1
      }
      this.changeOption()
    },
    // 格式化日期函数
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      // 返回格式化后的日期字符串，例如：YYYY-MM-DD
      return `${year}-${month}-${day}`;
    },

    // 创建一个微信支付二维码
    createQrCode(){
      // 避免创建重复的二维码 qrcode是追加元素
      if(this.$refs.payQrcode) this.$refs.payQrcode.innerHTML = ''

      new QRCode(this.$refs.payQrcode, {
        text: this.dataItem.updateImgUrl,
        width: 150,
        height: 150,
        colorDark: "#333333", //二维码颜色
        colorLight: "#ffffff", //二维码背景色
        // correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
      })
    },

    // 图片上传
    handleAvatarSuccess() {
      return (res, file, fileList) => {
        // 延迟3毫秒
        // setTimeout(() => {
          this.imgLoading = true
          const postData = {
            id: this.dataItem.id,
            imageUrl: res.info.imageUrl,
            type: 'add',
          }
          // console.log(postData)
          saveSiAccountImageData(postData)
            .then(res=>{
              if(res.error === 0){
                this.getImgData()
              } else {
                this.$errorMessage(res.message)
              }
              this.imgLoading = false
            })
        // }, 3000);
      }
    },

    beforeAvatarUpload(file) {
      if (this.imgArr.length >= 9) {
        this.$message.error(this.$t('shipment.上传的图片不得超过9张'));
        return false
      }
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt1M = file.size / 1024 / 1024 < 10;

      // this.uploadIng = true
      if (!isJPG) {
        // this.uploadIng = false
        this.$message.error(this.$t('shipment.上传的图片格式需为jpeg/png'));
      }
      if (!isLt1M) {
        // this.uploadIng = false
        this.$message.error(this.$t('shipment.上传的图片不得超过10M'));
      }
      return isJPG && isLt1M;
    },

    changeOption(is_search = false, type = ''){
      if (is_search === true) {
        //判断是否使用过搜索按钮
        this.is_search = true
      }
      if (type === 'clear') {
        if (this.is_search === false) {
          return
        } else {
          this.is_search = false
        }
      }

      this.queryParams.page = 1;
      this.getData()
    },

    handleSizeChange(val){
      this.queryParams.pageSize = val;
      this.queryParams.page = 1;
      this.getData();
    },

    accountChangeOption(is_search = false, type = ''){
      if (is_search === true) {
        //判断是否使用过搜索按钮
        this.is_search = true
      }
      if (type === 'clear') {
        if (this.is_search === false) {
          return
        } else {
          this.is_search = false
        }
      }

      this.accountQueryParams.page = 1;
      this.getAccountData()
    },
  },
}
</script>

<style scoped lang="scss">
::v-deep {
  .my-date-picker .el-input__inner{
    color: red;
  }
}
.wrap {
  padding: 30px 30px;
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }

}
.header-select{
  margin-right: 20px;
}
.form-tips{
  font-size: 12px;
}
.union-pay-title {
  font-weight: 900;
  font-size: 14px;
}
.zoomable-image {
  width: 178px;
  height: 138px;
  transition: transform 0.3s; /* 添加过渡效果，使放大效果更平滑 */
}
.zoomable-image:hover {
  transform: scale(1.2); /* 鼠标移入时放大 1.2 倍，可以根据需要调整 */
}
.close-icon {
  position: relative;
  top: -10px;
  left: -15px;
  font-size: 15px;
  cursor: pointer;
  color: white;
  border: 1px solid rgba(245, 108, 108, 1);
  background-color: rgba(245, 108, 108, 1);
  border-radius: 10px;
  width: 22px;
  height: 21px;
  text-align: center;
  transition: transform 0.3s;
  padding-left: 5px;
  padding-right: 5px;
  display: inline-block;
}
</style>
